package cn.jiaqiang.chatgpt.data.domain.openai.service.channel.impl;


import cn.jiaqiang.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.GenerativeModelVO;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.OpenAiGroupService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.model.IGenerativeModelService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.model.impl.ImageGenerativeModelServiceImpl;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.model.impl.TextGenerativeModelServiceImpl;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.impl.account.ReduceAccount;
import cn.jiaqiang.chatgpt.data.types.common.RedisConstants;
import cn.jiaqiang.chatgpt.data.types.enums.ChatGPTModel;
import cn.jiaqiang.chatgpt.data.types.exception.ChatGPTException;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.jiaqiang.chatgpt.common.Constants;
import com.jiaqiang.chatgpt.domain.chat.ChatChoice;
import com.jiaqiang.chatgpt.domain.chat.ChatCompletionRequest;
import com.jiaqiang.chatgpt.domain.chat.ChatCompletionResponse;
import com.jiaqiang.chatgpt.domain.chat.Message;
import com.jiaqiang.chatgpt.session.OpenAiSession;
import lombok.extern.slf4j.Slf4j;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @description ChatGPT 服务
 */
@Slf4j
@Service
public class ChatGPTService implements OpenAiGroupService {

    private final Map<GenerativeModelVO, IGenerativeModelService> generativeModelGroup = new HashMap<>();
    public ChatGPTService(ImageGenerativeModelServiceImpl imageGenerativeModelService, TextGenerativeModelServiceImpl textGenerativeModelService) {
        generativeModelGroup.put(GenerativeModelVO.IMAGES, imageGenerativeModelService);
        generativeModelGroup.put(GenerativeModelVO.TEXT, textGenerativeModelService);
    }

    @Override
    public void doMessageResponse(ChatProcessAggregate chatProcess, ResponseBodyEmitter emitter) throws Exception {
        GenerativeModelVO generativeModelVO = chatProcess.getGenerativeModelVO();
        generativeModelGroup.get(generativeModelVO).doMessageResponse(chatProcess, emitter);
    }


}
